package com.echo.distributedlock.api;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.lang.Nullable;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @author lmy
 */
public class ZooLock implements Lock {

    private final InterProcessMutex mutex;

    @Override
    public void lock() {
        try {
            mutex.acquire();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void lockInterruptibly() {
        throw new IllegalArgumentException();
    }

    @Override
    public boolean tryLock() {
        try {
            return mutex.acquire(0, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean tryLock(long time, @Nullable TimeUnit unit) {
        try {
            return mutex.acquire(time, unit);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void unlock() {
        try {
            mutex.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Condition newCondition() {
        throw new IllegalArgumentException();
    }

    public ZooLock(String key, CuratorFramework curatorFramework) {
        this.mutex = new InterProcessMutex(curatorFramework, key);
    }
}
